function getHistory(prefix="") {
	var history = window.localStorage.getItem(prefix+"history")
	if (!history) {
		history = new Array();
	} else {
		try {
			history = JSON.parse(history)
		} catch (e) {
			history = new Array();
		}
	}
	return history;
}


function saveHistory(history,prefix="") {
	window.localStorage.setItem(prefix+"history", JSON.stringify(history))
}

function delHistory(prefix="") {
	var del = confirm("确认清空记录?")
	if (!del) {
		return;
	}
	window.localStorage.removeItem(prefix+"history");
	window.location.reload();
}

function objectToFormUrlEncoded(obj) {
	let pairs = [];
	for (let key in obj) {
		if (obj.hasOwnProperty(key)) {
			pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
		}
	}
	return pairs.join('&');
}

function uniPage(link = "") {
	if (link == "") {
		link = '/pages/index/work'
	}
	uni.navigateTo({
		url: link
	})
}

function unidown(url, name) {
	uni.postMessage({
		data: {
			name: name,
			url: url,
		}
	})
}
//获取get参数
function GetParam(param = "") {
	var url = location.search; //获取url中"?"符后的字串
	var theRequest = new Object();
	if (url.indexOf("?") != -1) {
		var str = url.substr(1);
		strs = str.split("&");
		for (var i = 0; i < strs.length; i++) {
			theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
		}
	}
	if (param != "") {
		return theRequest[param] || "";
	}
	return theRequest;
}

function Filename(url) {
	if (url.lastIndexOf("?")>0){
		url= url.substring(0,url.lastIndexOf('?'))
	}

	url =  url.replace(/\\/g,'/');

	let filename = url.substring(url.lastIndexOf('/'))
	return filename
}

var book_map = {};
var srced =  false;
function book_src_init() {
	srced = true
	var book_src = localStorage.getItem("book_src");
	if (!book_src) {
		return;
	}
	var books = JSON.parse(book_src);
	if (!books) {
		return;
	}
	for (var k in books) {
		var book = books[k];
		console.log(book.host.slice(book.host.indexOf('.') + 1));
		book_map[book.host.slice(book.host.indexOf('.') + 1)] = book;
	}
	return book_map;
}

function book_src_get(link) {
	if(!book_map.length&&!srced){
		book_src_init();
	}
	console.log(Object.keys( book_map))
	for (var k of Object.keys( book_map)) {
		console.log(k)
		var uri = new URL(link)
		console.log(uri.host)
		console.log(link)
		console.log(uri.host.indexOf(k) >= 0)
		if (uri.host.indexOf(k) >= 0) {
			return book_map[k];
		}
	}
	return false;
}
//type=0 菜单 1章节
function check_src(type) {
	var url = $('input[name=url]').val();
	var uri = new URL(url);
	var bk_src = book_src_get(url);
	if (!bk_src) {
		console.log("无书源信息"+url)
		//alert("无书源信息"+url);
		return;
	}
	console.log(bk_src)
	$("#tags").val(bk_src.tags);
	$("#subpage").val(bk_src.subpage);
	url = url.replace(uri.host, bk_src.host)

	if (type == 1) {
		$('input[name=url]').val(url);
		var end_url = $('input[name=end_url]').val();
		end_url = end_url.replace(uri.host, bk_src.host);
		$('input[name=end_url]').val(end_url);
		alert("书源应用成功1");
		return;
	}
	$("#submenu").val(bk_src.submenu);
	$("#sort").val(bk_src.sort);
	console.log(bk_src)
	if(bk_src.prefix == 'undefined'){
		bk_src.prefix ="";
	}
	bk_src.prefix = bk_src.prefix.replace("｛bid｝","{bid}")
	console.log(bk_src)
	var bk_src_prefix = bk_src.prefix;
	if (bk_src.prefix.indexOf("{bid}")>=0 ) {
		var menu_url = url;
		if(bk_src.suffix){
			 menu_url =	url.replace(bk_src.suffix,"")
		}
			console.log("menu_url");
		console.log(menu_url);
		var quopos = menu_url.indexOf('?');
		if(quopos>=0){
			 menu_url = menu_url.substr(0,quopos)
		}
		
		var prf = menu_url.split("/");
		//书籍id大于1
		if(prf.length>=3){
			if(prf[prf.length - 3].length>1){
				bk_src_prefix =  bk_src.prefix.replace("{bid}",prf[prf.length - 3]) ;
			}
			if(prf[prf.length - 2].length>1){
				bk_src_prefix =  bk_src.prefix.replace("{bid}",prf[prf.length - 2]) ;
			}
			if(prf[prf.length - 1].length>1){
				bk_src_prefix =  bk_src.prefix.replace("{bid}",prf[prf.length - 1]);
			}
			bk_src_prefix =bk_src_prefix.replace(".html","");		
		}else{
			bk_src_prefix ="";
		}
	}
	console.log(bk_src.prefix);
	console.log(bk_src_prefix);
	$("#prefix").val(bk_src_prefix);
	if (bk_src.suffix && url.indexOf(bk_src.suffix) < 0) {
		url += bk_src.suffix
	}
	$('input[name=url]').val(url);
	alert("书源应用成功2");
}

function downloadZip(name,urls,text="",tips="#apiCbk") {
	var zip = new JSZip();
	var count = 0 ;
	var imgcount = 0;
	var txt = "";
	var tt = name;
	var selectNum = urls.length
	if (text!=""){
		zip.file("index.comic",text)
	}

	urls.forEach(function(vv, k) {
		imgcount+=1;
		var requrl = vv;
		if (requrl.indexOf('?') < 0) {
			//   requrl += "?response-content-type=application/octet-stream"
		} else {
			//   requrl += "&response-content-type=application/octet-stream"
		}
		var xhr = new XMLHttpRequest();
		// console.log( requrl)
		xhr.open("GET",requrl,true);
		xhr.responseType ="blob";
		// xhr.withCredentials = false;
		xhr.onload = function () {
			if (xhr.status===200) {
				var dir ="/" ;
				var no ="";



				var fileType = requrl;
				if (fileType.lastIndexOf("?")>0){
					fileType= fileType.substring(0,requrl.lastIndexOf('?'))
				}
				console.log( requrl)
				fileType =  fileType.replace(/\\/g,'/');
				console.log(   fileType)
				filename = Filename( requrl);
				fileType= fileType.substring(requrl.lastIndexOf('.'))
				if (fileType=='html'){
					fileType = "jpg";
				}

				console.log(filename)
				zip.folder(dir)
				zip.file(dir+"/"+filename,xhr.response)
			}
			count++;
			$(tips).html("进度:"+Math.ceil(100*count/selectNum)+"%")
			if (count==selectNum){
				$(tips).html("保存中,请勿关闭页面或刷新...")
				zip.generateAsync({type:"blob"}).then((content)=>{
					saveAs(content,name+".zip")
					$(tips).html("导出完成，打开浏览器下载解压后查看")


				})

			}


		}
		xhr.send();

	})
	if (imgcount==0){

		alert("无图片")

	}
}

//下载
function comicdown(name,v="",tips="#apiCbk") {
	var data = {
		"name": name,
	};
	var text ="";
	var xhr = new XMLHttpRequest();
	xhr.open("POST", "/api/comicOne", true);
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xhr.onreadystatechange = function() {
		if (xhr.readyState === 4 && xhr.status === 200) {
			var res = JSON.parse(xhr.responseText)
			if (res.Code == 0) {
				var path = res.Msg;
				if (v != "") {
					for (var k in  res.Data) {
						vv = res.Data[k];
						if (vv == '.' || vv == "..") {
							continue;
						}

						unidown(vv, '' + 'comic/' + name + '/' +  vv);

					}
				} else {
					downloadZip(name, res.Data,text,tips)
				}
			}else{
				alert("Error: " + xhr.responseText);
			}
		} else if (xhr.readyState === 4) {
			console.log(xhr.readyState)
			console.log(xhr.status)
			alert("网络异常");
		}
	}
	xhr.send(objectToFormUrlEncoded(data));
}

function openUrl(url){
	plus.runtime.openURL( url,(err)=>{
		console.log(err)
	})
}